#pragma once

#include <iostream>
#include <filesystem>
#include <fstream>
#include <memory>
#include <time.h>
#include <unistd.h>
#include <string>
#include <sstream>
#include "Mutex.hpp"


namespace LogModel
{

    // 日志文件默认的路径
    std::string defaultlopath = "./log/";
    const std::string defaultname = "log.txt";
    using namespace LockMutex;

    // 获取当前系统的时间
    std::string CurrenTime()
    {
        time_t time_stamp = ::time(nullptr);
        struct tm curr;
        localtime_r(&time_stamp, &curr); // 时间戳,获取可读取较强的时间信息
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 curr.tm_year,
                 curr.tm_mon,
                 curr.tm_mday,
                 curr.tm_hour,
                 curr.tm_min,
                 curr.tm_sec);
        return buffer;
    }
    // 日志等级
    enum class LgoLevel
    {
        DEBUG = 1,
        INFo,
        WARNING,
        EROR,
        TATAL
    };

    // 将日志等级转换成字符串
    std::string LgoLevelstr(LgoLevel level)
    {
        switch (level)
        {
        case LgoLevel::DEBUG:
            return "DEBUG";
        case LgoLevel::INFo:
            return "INFo";
        case LgoLevel::WARNING:
            return "WARNING";
        case LgoLevel::EROR:
            return "EROR";
        case LgoLevel::TATAL:
            return "TATAL";
        default:
            return "NONE";
        }
    }

    // 刷新策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    // 控制台策略
    class ConsoIeLogStrategy : public LogStrategy
    {
    public:
        ConsoIeLogStrategy() {};
        ~ConsoIeLogStrategy() {};

        void SyncLog(const std::string &message)
        {
            LockGurd lockgurd(_lock);
            std::cout << message << std::endl;
        }

    private:
        mutex _lock;
    };

    // 文件(磁盘)策略
    class FiieLogStrategy : public LogStrategy
    {
    public:
        FiieLogStrategy(std::string logpath = defaultlopath, std::string logname = defaultname)
            : _logpath(logpath), _logname(logname)
        {
            if (std::filesystem::exists(_logpath))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }
        ~FiieLogStrategy() {};
        void SyncLog(const std::string &message)
        {
            LockGurd lockgurd(_lock);
            std::string log = _logpath + _logname;
            std::ofstream out(log, std::ios::app); // 日志写入一定是追加
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }

    private:
        std::string _logpath;
        std::string _logname;
        mutex _lock;
    };

    // 日志类,构件日志字符串,跟课策略进行刷新
    class Logger
    {
    public:
        Logger()
        {
            // 默认采用ConsoleLogStrategy策略
            _strategy = std::make_shared<ConsoIeLogStrategy>();
        }
        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConsoIeLogStrategy>();
        }
        void EnbleFileLog()
        {
            _strategy = std::make_shared<FiieLogStrategy>();
        }
        ~Logger() {}

        class LogMessage
        {
        public:
            LogMessage(LgoLevel level, std::string &filename, int line, Logger &logger)
                : _level(level),
                  _currtime(CurrenTime()),
                  _pid(getpid()),
                  _filename(filename),
                  _line(line),
                  _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _currtime << "]"
                         << "[" << LgoLevelstr(_level) << "]"
                         << "[" << _pid << "]"
                         << "[" << _filename << "]"
                         << "[" << _line << "]"
                         << "-";
                _loginfo = ssbuffer.str();
            }

            template <typename T>
            LogMessage &operator<<(const T info)
            {
                std::stringstream ssbuffer;
                ssbuffer << info;
                _loginfo += ssbuffer.str();

                return *this; // 返回当前LogMessage对象,.⽅便下次继续进⾏<<
            }

            ~LogMessage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->SyncLog(_loginfo);
                }
            }

        private:
            std::string _currtime; // 当前日志的时间
            LgoLevel _level;       // 日志等级
            pid_t _pid;            // 进程id
            std::string _filename; // 源文件名称
            int _line;             // 日志的行号
            Logger &_logger;       // 负责根据不同的策略进程刷新
            std::string _loginfo;  // 一条完整的日记记录
        };
        LogMessage operator()(LgoLevel level, std::string filename, int line)
        {
            return LogMessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy; // 智能指针,日志刷新的策略方案
    };

    // 定义一个全局的对象
    Logger log;

    #define LOG(LgoLevel) log(LgoLevel,__FILE__,__LINE__)

    #define ENABLECONSOLELOG() log.EnableConsoleLog()

    #define ENBLEFILELOG() log.EnbleFileLog()


}